package org.jeecg.modules.oms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.oms.entity.CfAccessoriesTable;
import org.jeecg.modules.oms.entity.CfGlassSizeTable;
import org.jeecg.modules.oms.entity.CfInnerSashSizeTable;
import org.jeecg.modules.oms.entity.CfProfileSizeTable;
import org.jeecg.modules.oms.entity.ProductSalesOrderDetail;
import org.jeecg.modules.oms.mapper.CfAccessoriesTableMapper;
import org.jeecg.modules.oms.mapper.CfGlassSizeTableMapper;
import org.jeecg.modules.oms.mapper.CfInnerSashSizeTableMapper;
import org.jeecg.modules.oms.mapper.CfProfileSizeTableMapper;
import org.jeecg.modules.oms.mapper.XgeAccessoriesTableMapper;
import org.jeecg.modules.oms.mapper.XgeGlassSizeTableMapper;
import org.jeecg.modules.oms.mapper.XgeProfileSizeTableMapper;
import org.jeecg.modules.oms.service.ICfWindowDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 长风窗型确认文件数据服务实现类
 */
@Service
public class CfWindowDataServiceImpl implements ICfWindowDataService {

    @Autowired
    private CfProfileSizeTableMapper profileSizeTableMapper;
    
    @Autowired
    private CfGlassSizeTableMapper glassSizeTableMapper;
    
    @Autowired
    private CfInnerSashSizeTableMapper innerSashSizeTableMapper;
    
    @Autowired
    private CfAccessoriesTableMapper accessoriesTableMapper;
    
    @Autowired
    private XgeAccessoriesTableMapper xgeAccessoriesTableMapper;
    
    @Autowired
    private XgeGlassSizeTableMapper xgeGlassSizeTableMapper;
    
    @Autowired
    private XgeProfileSizeTableMapper xgeProfileSizeTableMapper;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveProfileSizeTable(String detailId, Integer tenantId, JSONArray jsonArray) {
        if (jsonArray == null || jsonArray.isEmpty()) {
            return true;
        }
        
        // 先删除原有数据
        profileSizeTableMapper.deleteByDetailId(detailId);
        
        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = loginUser != null ? loginUser.getUsername() : "";
        Date now = new Date();
        
        // 批量插入新数据
        List<CfProfileSizeTable> dataList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            CfProfileSizeTable data = new CfProfileSizeTable();
            
            data.setId(UUID.randomUUID().toString().replace("-", ""));
            data.setDetailId(detailId);
            data.setTenantId(tenantId);
            data.setSerialNo(i + 1);
            
            // 提取数据
            if (jsonObject.containsKey("序号")) {
                try {
                    data.setSerialNo(Integer.parseInt(jsonObject.getString("序号")));
                } catch (NumberFormatException e) {
                    // 使用默认序号
                }
            }
            
            if (jsonObject.containsKey("型材代码")) {
                data.setProfileCode(jsonObject.getString("型材代码"));
            }
            
            if (jsonObject.containsKey("型材名称")) {
                data.setProfileName(jsonObject.getString("型材名称"));
            }
            
            if (jsonObject.containsKey("规格")) {
                data.setSpecification(jsonObject.getString("规格"));
            }
            
            if (jsonObject.containsKey("数量")) {
                try {
                    data.setQuantity(Integer.parseInt(jsonObject.getString("数量")));
                } catch (NumberFormatException e) {
                    // 忽略转换异常
                }
            }
            
            if (jsonObject.containsKey("长度")) {
                try {
                    data.setLength(Double.parseDouble(jsonObject.getString("长度")));
                } catch (NumberFormatException e) {
                    // 忽略转换异常
                }
            }
            
            if (jsonObject.containsKey("单位")) {
                data.setUnit(jsonObject.getString("单位"));
            }

            if (jsonObject.containsKey("类别")) {
                data.setCategory(jsonObject.getString("类别"));
            }

            if (jsonObject.containsKey("备注")) {
                data.setRemark(jsonObject.getString("备注"));
            }
            
            // 设置创建和更新信息
            data.setCreateBy(username);
            data.setCreateTime(now);
            data.setUpdateBy(username);
            data.setUpdateTime(now);
            
            dataList.add(data);
        }
        
        // 批量插入
        for (CfProfileSizeTable data : dataList) {
            profileSizeTableMapper.insert(data);
        }
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveGlassSizeTable(String detailId, Integer tenantId, JSONArray jsonArray) {
        if (jsonArray == null || jsonArray.isEmpty()) {
            return true;
        }
        
        // 先删除原有数据
        glassSizeTableMapper.deleteByDetailId(detailId);
        
        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = loginUser != null ? loginUser.getUsername() : "";
        Date now = new Date();
        
        // 批量插入新数据
        List<CfGlassSizeTable> dataList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            CfGlassSizeTable data = new CfGlassSizeTable();
            
            data.setId(UUID.randomUUID().toString().replace("-", ""));
            data.setDetailId(detailId);
            data.setTenantId(tenantId);
            data.setSerialNo(i + 1);
            
            // 提取数据
            if (jsonObject.containsKey("序号")) {
                try {
                    data.setSerialNo(Integer.parseInt(jsonObject.getString("序号")));
                } catch (NumberFormatException e) {
                    // 使用默认序号
                }
            }
            
            if (jsonObject.containsKey("玻璃宽")) {
                try {
                    data.setGlassWidth(Double.parseDouble(jsonObject.getString("玻璃宽")));
                } catch (NumberFormatException e) {
                    // 忽略转换异常
                }
            }
            
            if (jsonObject.containsKey("玻璃高")) {
                try {
                    data.setGlassHeight(Double.parseDouble(jsonObject.getString("玻璃高")));
                } catch (NumberFormatException e) {
                    // 忽略转换异常
                }
            }
            
            if (jsonObject.containsKey("数量")) {
                try {
                    data.setQuantity(Integer.parseInt(jsonObject.getString("数量")));
                } catch (NumberFormatException e) {
                    // 忽略转换异常
                }
            }
            
            if (jsonObject.containsKey("玻璃种类")) {
                data.setGlassType(jsonObject.getString("玻璃种类"));
            }
            
            // 设置创建和更新信息
            data.setCreateBy(username);
            data.setCreateTime(now);
            data.setUpdateBy(username);
            data.setUpdateTime(now);
            
            dataList.add(data);
        }
        
        // 批量插入
        for (CfGlassSizeTable data : dataList) {
            glassSizeTableMapper.insert(data);
        }
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveInnerSashSizeTable(String detailId, Integer tenantId, JSONArray jsonArray) {
        if (jsonArray == null || jsonArray.isEmpty()) {
            return true;
        }
        
        // 先删除原有数据
        innerSashSizeTableMapper.deleteByDetailId(detailId);
        
        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = loginUser != null ? loginUser.getUsername() : "";
        Date now = new Date();
        
        // 批量插入新数据
        List<CfInnerSashSizeTable> dataList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            CfInnerSashSizeTable data = new CfInnerSashSizeTable();
            
            data.setId(UUID.randomUUID().toString().replace("-", ""));
            data.setDetailId(detailId);
            data.setTenantId(tenantId);
            data.setSerialNo(i + 1);
            
            // 提取数据
            if (jsonObject.containsKey("序号")) {
                try {
                    data.setSerialNo(Integer.parseInt(jsonObject.getString("序号")));
                } catch (NumberFormatException e) {
                    // 使用默认序号
                }
            }
            
            if (jsonObject.containsKey("内扇")) {
                data.setInnerSash(jsonObject.getString("内扇"));
            }
            
            if (jsonObject.containsKey("规格")) {
                data.setSpecification(jsonObject.getString("规格"));
            }
            
            if (jsonObject.containsKey("数量")) {
                try {
                    data.setQuantity(Integer.parseInt(jsonObject.getString("数量")));
                } catch (NumberFormatException e) {
                    // 忽略转换异常
                }
            }
            
            if (jsonObject.containsKey("宽度")) {
                try {
                    data.setWidth(Double.parseDouble(jsonObject.getString("宽度")));
                } catch (NumberFormatException e) {
                    // 忽略转换异常
                }
            }
            
            if (jsonObject.containsKey("高度")) {
                try {
                    data.setHeight(Double.parseDouble(jsonObject.getString("高度")));
                } catch (NumberFormatException e) {
                    // 忽略转换异常
                }
            }
            
            if (jsonObject.containsKey("单位")) {
                data.setUnit(jsonObject.getString("单位"));
            }
            
            // 设置创建和更新信息
            data.setCreateBy(username);
            data.setCreateTime(now);
            data.setUpdateBy(username);
            data.setUpdateTime(now);
            
            dataList.add(data);
        }
        
        // 批量插入
        for (CfInnerSashSizeTable data : dataList) {
            innerSashSizeTableMapper.insert(data);
        }
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAccessoriesTable(String detailId, Integer tenantId, JSONArray jsonArray) {
        if (jsonArray == null || jsonArray.isEmpty()) {
            return true;
        }
        
        // 先删除原有数据
        accessoriesTableMapper.deleteByDetailId(detailId);
        
        // 获取当前登录用户
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = loginUser != null ? loginUser.getUsername() : "";
        Date now = new Date();
        
        // 批量插入新数据
        List<CfAccessoriesTable> dataList = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            CfAccessoriesTable data = new CfAccessoriesTable();
            
            data.setId(UUID.randomUUID().toString().replace("-", ""));
            data.setDetailId(detailId);
            data.setTenantId(tenantId);
            data.setSerialNo(i + 1);
            
            // 提取数据
            if (jsonObject.containsKey("序号")) {
                try {
                    data.setSerialNo(Integer.parseInt(jsonObject.getString("序号")));
                } catch (NumberFormatException e) {
                    // 使用默认序号
                }
            }
            
            if (jsonObject.containsKey("配件名称")) {
                data.setAccessoryCode(jsonObject.getString("配件名称"));
                data.setAccessoryName(jsonObject.getString("配件名称"));
            }
            
            if (jsonObject.containsKey("规格")) {
                data.setSpecification(jsonObject.getString("规格"));
            }
            
            if (jsonObject.containsKey("数量")) {
                try {
                    data.setQuantity(Integer.parseInt(jsonObject.getString("数量")));
                } catch (NumberFormatException e) {
                    // 忽略转换异常
                }
            }
            
            if (jsonObject.containsKey("单位")) {
                data.setUnit(jsonObject.getString("单位"));
            }
            
            if (jsonObject.containsKey("品牌")) {
                data.setBrand(jsonObject.getString("品牌"));
            }
            
            if (jsonObject.containsKey("partIndex")) {
                data.setPartIndex(jsonObject.getInteger("partIndex"));
            } else {
                data.setPartIndex(1); // 默认为第一部分
            }
            
            // 设置创建和更新信息
            data.setCreateBy(username);
            data.setCreateTime(now);
            data.setUpdateBy(username);
            data.setUpdateTime(now);
            
            dataList.add(data);
        }
        
        // 批量插入
        for (CfAccessoriesTable data : dataList) {
            accessoriesTableMapper.insert(data);
        }
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAllWindowData(ProductSalesOrderDetail detail) {
        if (detail == null || detail.getId() == null) {
            return false;
        }
        
        String detailId = detail.getId();
        Integer tenantId = detail.getTenantId();
        
        // 保存型材尺寸表数据
        if (!StringUtils.isEmpty(detail.getProfileSizeTableJson())) {
            JSONArray profileSizeTable = JSON.parseArray(detail.getProfileSizeTableJson());
            saveProfileSizeTable(detailId, tenantId, profileSizeTable);
        }
        
        // 保存玻璃尺寸表数据
        if (!StringUtils.isEmpty(detail.getGlassSizeTableJson())) {
            JSONArray glassSizeTable = JSON.parseArray(detail.getGlassSizeTableJson());
            saveGlassSizeTable(detailId, tenantId, glassSizeTable);
        }
        
        // 保存内扇尺寸表数据
        if (!StringUtils.isEmpty(detail.getInnerSashSizeTableJson())) {
            JSONArray innerSashSizeTable = JSON.parseArray(detail.getInnerSashSizeTableJson());
            saveInnerSashSizeTable(detailId, tenantId, innerSashSizeTable);
        }
        
        // 保存配件表数据
        if (!StringUtils.isEmpty(detail.getAccessoriesTableJson())) {
            JSONArray accessoriesTable = JSON.parseArray(detail.getAccessoriesTableJson());
            saveAccessoriesTable(detailId, tenantId, accessoriesTable);
        }
        
        return true;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteAllByDetailId(String detailId) {
        if (StringUtils.isEmpty(detailId)) {
            return false;
        }
        
        // 删除各表数据
        profileSizeTableMapper.deleteByDetailId(detailId);
        glassSizeTableMapper.deleteByDetailId(detailId);
        innerSashSizeTableMapper.deleteByDetailId(detailId);
        accessoriesTableMapper.deleteByDetailId(detailId);
        
        return true;
    }
    
    @Override
    public List<Map<String, Object>> getAccessoriesByDetailId(String detailId) {
        return accessoriesTableMapper.getAccessoriesByDetailId(detailId);
    }
    
    @Override
    public List<Map<String, Object>> getAccessoriesByDetailIdAndWindowNo(String detailId, String windowNo) {
        return accessoriesTableMapper.getAccessoriesByDetailIdAndWindowNo(detailId, windowNo);
    }
    
    @Override
    public List<Map<String, Object>> getGlassSizeByDetailId(String detailId) {
        return glassSizeTableMapper.getGlassSizeByDetailId(detailId);
    }
    
    @Override
    public List<Map<String, Object>> getGlassSizeByDetailIdAndWindowNo(String detailId, String windowNo) {
        return glassSizeTableMapper.getGlassSizeByDetailIdAndWindowNo(detailId, windowNo);
    }
    
    @Override
    public List<Map<String, Object>> getProfileSizeByDetailId(String detailId) {
        return profileSizeTableMapper.getProfileSizeByDetailId(detailId);
    }
    
    @Override
    public List<Map<String, Object>> getProfileSizeByDetailIdAndWindowNo(String detailId, String windowNo) {
        return profileSizeTableMapper.getProfileSizeByDetailIdAndWindowNo(detailId, windowNo);
    }
    
    @Override
    public List<Map<String, Object>> getXgeAccessoriesByDetailId(String detailId) {
        return xgeAccessoriesTableMapper.getXgeAccessoriesByDetailId(detailId);
    }
    
    @Override
    public List<Map<String, Object>> getXgeAccessoriesByDetailIdAndWindowNo(String detailId, String windowNo) {
        return xgeAccessoriesTableMapper.getXgeAccessoriesByDetailIdAndWindowNo(detailId, windowNo);
    }
    
    @Override
    public List<Map<String, Object>> getXgeGlassSizeByDetailId(String detailId) {
        return xgeGlassSizeTableMapper.getXgeGlassSizeByDetailId(detailId);
    }
    
    @Override
    public List<Map<String, Object>> getXgeGlassSizeByDetailIdAndWindowNo(String detailId, String windowNo) {
        return xgeGlassSizeTableMapper.getXgeGlassSizeByDetailIdAndWindowNo(detailId, windowNo);
    }
    
    @Override
    public List<Map<String, Object>> getXgeProfileSizeByDetailId(String detailId) {
        return xgeProfileSizeTableMapper.getXgeProfileSizeByDetailId(detailId);
    }
    
    @Override
    public List<Map<String, Object>> getXgeProfileSizeByDetailIdAndWindowNo(String detailId, String windowNo) {
        return xgeProfileSizeTableMapper.getXgeProfileSizeByDetailIdAndWindowNo(detailId, windowNo);
    }
} 